﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using BallotCounter.Question;

namespace BallotCounter.Answer
{
    class Albin : IBallotCounter
    {
        public int BallotCount(int[] ballotArray)
        {
            int n = 16777216;
            
            int count = -1;
            int flag = 0;
            int len = ballotArray.Length;
            int result = -1;
            if (ballotArray.Length == 0)
                return -1;

            Stack<int>[] st = new Stack<int>[256];
            for (int i = 0; i < len; i++)
            {
                int row = ballotArray[i] / n;
                int line = ballotArray[i] % n;
                if (line < 0 || line > n)
                    return -1;
                if (st[row] == null)
                {
                    st[row] = new Stack<int>();
                }
                st[row].Push( line);
            }
          
            for (int i = 0; i < 256; i++)
            {
                if (st[i] != null)
                {
                    int[] arr = new int[n];
                    while (st[i].Count > 0)
                    {
                        int num = st[i].Pop();
                        arr[num]++;
                        if (count == arr[num])
                        {
                            flag = 1;
                        }
                        if (count < arr[num])
                        {
                            count = arr[num];
                            flag = 0;
                            result = num + i * n;
                            if (len % 2 == 0)
                            {
                                if (count > len / 2)
                                    return result;
                            }
                            else
                            {
                                if (count > len / 2 + 1)
                                    return result;
                            }
                        }
                    }
                }
            }
            if(flag == 0)
                return result;
            else
                return -1;
        }
    }
}
